<?php

namespace api\request;

use api\lib\Str;

class DomainQueryRequest extends Request
{
    const POS_BEGIN = 1;  // 开头
    const POS_END = 2; // 结尾
    const POS_MIDDLE = 3; // 中间

    private static function isValidPos(/* int */$pos) {
        return $pos == self::POS_BEGIN || $pos == self::POS_END || $pos == self::POS_MIDDLE;
    }

    public function validateParams(/* array */$params, /* array */&$invalidParams) {
        $invalidParams = array();
        if (isset($params['domain'])) {
            if (!isset($params['domain']['contains'])) {
                $invalidParams[] = ['domain.contains', 'required'];
            }
            if (!isset($params['domain']['pos'])) {
                $invalidParams[] = ['domain.pos', 'required'];
            } else {
                $pos = $params['domain']['pos'];
                if (!self::isValidPos($pos)) {
                    $invalidParams[] = ['domain.pos', "domain.pos is must be in [".
                        implode(',', [self::POS_BEGIN, self::POS_END, self::POS_MIDDLE])."]"];
                }
            }
        }
        if (isset($params['deletion_date'])) {
            $date = $params['deletion_date'];
            $dateTime = $date." 00:00:00";
            if (!Str::isValidDateTime($dateTime)) {
                $invalidParams[] = ['deletion_date', 'invalid yyyy-mm-dd'];
            }
        }
        // 默认页码 每页大小
        if (!isset($params['page'])) {
            $params['page'] = 1;
        }
        if (!isset($params['size'])) {
            $params['size'] = 10;
        }
        return $params;
    }

    public function getJsonParams() {
        $body = $this->getBody();
        $a = json_decode($body, true);
        if (empty($a)) {
            throw new \InvalidArgumentException("Invalid POST JSON");
        }
        return $a;
    }
}